package com.tehui.utils.web;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.utils.ui.UiUtils;
import com.tehui.view.DownLoadDialog;
import com.tehui.view.UpdateDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;

import static com.tehui.app.MyApplication.IS_TAOKE;

/**
 * Created by jasmine on 2017/5/17.
 */
//升级apk
public class Update {

    private int            fileSize;
    private UpdateDialog   updateDialog;
    private DownLoadDialog downLoadDialog;
    private Context        context;

    public Update(Context context) {
        this.context = context;
    }

    public void getServreUpdate(final boolean isAbout) {

        int versionCode = UiUtils.getVersionCode();
        if (!UiUtils.isNetworkAvailable()) {
            UiUtils.toast("请检查网络!");
            return;
        }

        //测试内部接口   http://dl.21tehui.com/AppUpdate/inward.html?versions=
        //正式接口   http://dl.21tehui.com/AppUpdate.html?versions=
        OkGo.get("http://dl.21tehui.com/AppUpdate.html?versions=" + 3).tag(this).cacheKey
                ("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (s != null) {
                    if (s.equals("-1") && isAbout) {
                        UiUtils.toast("已经是最新版本");
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String version = (String) jsonObject.get("version");
                            String msg = (String) jsonObject.get("msg");
                            fileSize = ((int) jsonObject.get("fileSize")) * 1024 / 100;

                            String[] split = msg.split("&");
                            String body = "";
                            for (String s1 : split) {
                                body = body + s1 + "\n";
                            }
                            showUpdateDialog(body, version);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    UiUtils.toast("获取数据出错,请稍候重试!");
                }
            }
        });
    }

    /**
     * 显示升级信息的对话框
     */
    private void showUpdateDialog(String msg, String version) {
        updateDialog = new UpdateDialog(context);
        updateDialog.setTitle("发现新版本");
        updateDialog.setMessage(msg);
        updateDialog.setVersion("最新版本 : " + version);
        updateDialog.setYesOnclickListener("更新", new UpdateDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                updateDialog.dismiss();
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    downFile();//点击确定将apk下载
                    UiUtils.toast("开始下载");
                } else {
                    UiUtils.toast("SD卡不可用，请插入SD卡");
                }
            }
        });
        updateDialog.setNoOnclickListener("取消", new UpdateDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                updateDialog.dismiss();
            }
        });
        updateDialog.show();
    }

    /**
     * 下载最新版本的apk
     */
    private void downFile() {
        String taokeId = context.getString(R.string.taokeId);
        downLoadDialog = new DownLoadDialog(context);
        downLoadDialog.show();
        downLoadDialog.setNoOnclickListener(new DownLoadDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                downLoadDialog.dismiss();
                OkGo.getInstance().cancelTag("download");
            }
        });

        //URL url = new URL("http://dl.21tehui.com/AppUpdate/updates.html?appName=" + appName);  10个apk
        //正式连接 http://dl.21tehui.com/AppUpdate/update.html
        //内部测试连接 http://dl.21tehui.com/AppUpdate/inwardAppDown.html
        //推广链接 http://dl.21tehui.com/AppUpdate/update.html?taokeId=

        if (IS_TAOKE) {
            OkGo.get("http://dl.21tehui.com/AppUpdate/update.html?taokeId=" + taokeId).tag("download")//
                    .execute(new FileCallback("21tehui.apk") {
                        @Override
                        public void onSuccess(File file, Call call, Response response) {
                            // file 即为文件数据，文件保存在指定目录
                            installApk();
                        }

                        @Override
                        public void downloadProgress(long currentSize, long totalSize, float progress, long
                                networkSpeed) {
                            //这里回调下载进度
                            downLoadDialog.setProgressNum((int) (Math.round(currentSize / fileSize) * 1.0f));
                        }
                    });
        } else {
            OkGo.get("http://dl.21tehui.com/AppUpdate/update.html").tag("download")//
                    .execute(new FileCallback("21tehui.apk") {
                        @Override
                        public void onSuccess(File file, Call call, Response response) {
                            // file 即为文件数据，文件保存在指定目录
                            installApk();
                        }

                        @Override
                        public void downloadProgress(long currentSize, long totalSize, float progress, long
                                networkSpeed) {
                            //这里回调下载进度
                            downLoadDialog.setProgressNum((int) (Math.round(currentSize / fileSize) * 1.0f));
                        }
                    });
        }
    }

    private void installApk() {
        //pBar.cancel();
        downLoadDialog.dismiss();
        File file = new File("/sdcard/download/", "21tehui.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判断版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(context, "com.tehui.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}
